package Java工具收集;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import lombok.AllArgsConstructor;
import lombok.Data;

public class JavaFileAttributeUtils {
	
	/**
	 * @function 从文件中读取属性
	 * @param filePath 文件绝对路径
	 * @author 肖荣辉
	 * @date 2021年7月23日
	*/
	public static List<Attribute> ReadAttributeFromFile(String filePath) throws Exception {
	
		File file = new File(filePath);
		
		FileInputStream fis = new FileInputStream(file);
		
		InputStreamReader isr = new InputStreamReader(fis);
		
		BufferedReader br = new BufferedReader(isr);
		
		String temp = null;
		
		//匹配注释里的文字说明
		String reg = "/\\*+([\\s\\S^\\*]*)(\\*/)$";
		String reg2 = "^//+([\\s\\S^]*)";
		String reg3 = "^private\\s+([\\S]+)\\s+([\\S]+)(\\s\\S)*\\s*;$";
		
		Pattern  pattern = Pattern.compile(reg);
		Pattern  pattern2 = Pattern.compile(reg2);
		Pattern  pattern3 = Pattern.compile(reg3);
		
		//上一个属性的备注
		String comment = "";
		
		List<Attribute> attributeList = new ArrayList<Attribute>();
		
		while((temp = br.readLine()) != null){
			
			temp = temp.trim();
			
			if(StringUtils.isBlank(temp))
				continue;
			
			Matcher matcher = pattern.matcher(temp);
			Matcher matcher2 = pattern2.matcher(temp);
			
			matcher = matcher.matches() ? matcher : matcher2;
			
			if(matcher.matches()) {
				comment = matcher.group(1);
				System.out.println(comment);
			}
			
			
			Matcher matcher3 = pattern3.matcher(temp);
			
			if(matcher3.matches()) {
				attributeList.add(new Attribute(matcher3.group(2) , comment , matcher3.group(1)));
				comment = "";
			}
			 
		}
		
		br.close();
		
		return attributeList;
	}
	
	@Data
	@AllArgsConstructor
	public static class Attribute {
		
		//属性名称
		private String name;
		
		//属性备注
		private String comment;
		
		//属性类型
		private String type;
	}
	
}
